import { defineStore } from 'pinia'
import request from '@/utils/request'
import { resultItem, ApiRes, TopCategory, ApiResObj, SubCategory } from '@/types/data'
import { topCategory } from '../constants'

// ctrl + 0 + k 快速折叠代码  ctrl + k + j 快速展开代码
// 处理默认常量数据
const topCategoryDefault = topCategory.map(item => {
  return { name: item }
})
const useCategoryStore = defineStore('category', {
  state() {
    return {
      list: topCategoryDefault as resultItem[],
      // 一级分类
      topCategory: {} as TopCategory,
      // 二级分类
      subCategory: {} as SubCategory,
    }
  },
  actions: {
    // 获取头部分类数据的方法
    async getCateList() {
      const res = await request.get<ApiRes<resultItem>>('/home/category/head')
      // console.log(res.data.result);
      res.data.result.forEach(item => item.open = false)
      this.list = res.data.result
    },
    // 显示
    show(id: string) {
      const obj = this.list.find(item => item.id === id)
      obj!.open = true
    },
    // 隐藏
    hide(id: string) {
      const obj = this.list.find(item => item.id === id)
      obj!.open = false
    },
    // 获取一级分类的详细信息
    async getTopCategory(id: string) {
      // get 添加query查询参数
      // const res = await request.get(`/category?id=${id}`)
      const res = await request.get<ApiResObj<TopCategory>>(`/category`, { params: { id } })
      this.topCategory = res.data.result
    },
    // 获取二级分类的详细信息
    async getSubFilter(id: string) {
      const res = await request.get<ApiResObj<SubCategory>>('/category/sub/filter', { params: { id } })
      this.subCategory = res.data.result
    }

  }
})
export default useCategoryStore